﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BOW
{
    public partial class EnterQuery : Form
    {
        public EnterQuery()
        {
            InitializeComponent();
        }
        public string a = "";
        public string path = "";
        int N;       
        double BR_length;
        double d_avg;
        double k1 = 1.2;
        double b = 0.5;
        double threshold = 0.9;  // Ngưỡng xác định trùng lặp
        public DesignControls des = new DesignControls();
        ConnectDB connect = new ConnectDB();
       // Const con = new Const();
        List<string> Str = new List<string>();// chứa field được chọn
        Common commo = new Common();
        Calculator cal = new Calculator();
        Dictionary<string, double> bug_duplicate = new Dictionary<string, double>();// contain bug duplicate
        Dictionary<string, double> temp_duplicate = new Dictionary<string, double>();
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
        private void EnterQuery_Load(object sender, EventArgs e)
        {
            BuildControls();
        }
      
        private void btnSave_Click(object sender, EventArgs e)
        {
            List<string> field = new List<string>();
            foreach (Control item in groupBox1.Controls)
            {
                field.Add(item.Text);
            }

            GetFieldCheck();// Trả ra chuỗi field được chọn
            string BugCurrent = "";// Bug current
            foreach (Control item in groupBox1.Controls)
            {
                if (item.GetType().Name == "TextBox")
                {
                    foreach (string s in Str)
                    {
                        if (s == item.Name)
                        {
                            BugCurrent += item.Text + " ";
                        }
                    }
                }
            }
            if (BugCurrent != "")
            {
                CheckDulicate(BugCurrent);
            }
            VisibleBtn();
        }

        public void CheckDulicate(string bug)
        {
            DataTable dtBuild = connect.getDataFromXLS(path);
            Dictionary<string, double> bug_new = new Dictionary<string, double>();
            bug_new = cal.Create_Vecto(bug); //chuyển bug mới nhập thành vecto

            Dictionary<string, double> getBOW = new Dictionary<string, double>();
            getBOW = commo.ReadBagOfWord();
            N = dtBuild.Rows.Count;
            double avg = getBOW.Count/N;
            for (int i = 0; i < dtBuild.Rows.Count; i++)
            {
                string s="";
                foreach (string t in Str)
                {
                        s+= dtBuild.Rows[i][t].ToString();
                }
                Dictionary<string, double> bug_old = new Dictionary<string, double>();
                bug_old = cal.Create_Vecto(s);
                bool check = cal.Compare_Vecto(bug_new, bug_old, threshold); // so sánh bug mới nhập và bug cũ
                if (bug_new.Count >= avg && bug_old.Count >= avg)
                {
                    if (check == false) // nếu lớn hơn  ngưỡng cho phép
                    {
                        bug_duplicate.Add(s, 1);
                    }
                }
                if (bug_new.Count < avg && bug_old.Count < avg)
                {
                    if (check == false) // nếu lớn hơn  ngưỡng cho phép
                    {
                        temp_duplicate.Add(s, 1);
                    }
                }
            }
        }
     
        public void BuildControls()
        {
            try
            {
                DataTable dtBuild = connect.getDataFromXLS(path);
                int i = 20;
                foreach (DataColumn item in dtBuild.Columns)
                {
                    var lbl = new Label();
                    lbl.Name = "lbl" + item.ToString();
                    lbl.Text = item.ToString() + ":";
                    lbl.AutoSize = true;
                    lbl.Location = new Point(10, 30 + i);
                    lbl.Size = new Size(50, 50);


                    var txtBox = new TextBox();
                    txtBox.Name = item.ToString();
                    txtBox.Location = new Point(150, 20 + i);
                    txtBox.Size = new Size(200, 20);
                    i += 30;
                    groupBox1.Size = new Size(500, 50 + i);
                    groupBox1.Controls.Add(lbl);
                    groupBox1.Controls.Add(txtBox);

                    groupBox2.Location = new Point(180, 123 + i);
                    //dataGridView1.Location = new Point(120 + i, 80);
                    //dataGridView1.Size = new Size(600, 200);
                    groupBox3.Location = new Point(120 + i, 80);
                    groupBox3.Size = new Size(600, 200);
                   
                    //dataGridView2.Location = new Point(120 + i, 300);
                    //dataGridView2.Size = new Size(600, 150);
                    groupBox4.Location = new Point(120 + i, 300);
                    groupBox4.Size = new Size(600, 150);
                    //gvTemp.Location = new Point(120 + i, 500);
                    //gvTemp.Size = new Size(600,200);
                    groupBox5.Location = new Point(120 + i, 500);
                    groupBox5.Size = new Size(600, 200);
                }
            }
            catch{}
        }

        public List<string> GetFieldCheck()
        {
            if (!string.IsNullOrEmpty(a))
            {
                while (a != string.Empty)
                {
                    Str.AddRange(a.Split('_'));
                    a = "";
                }
            }
            return Str;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            DataTable dtBuild = connect.getDataFromXLS(path);
            Dictionary<string, double> BOW = new Dictionary<string, double>();
            Dictionary<string, double> ListResult = new Dictionary<string, double>();
            if (dtBuild.Rows.Count > 0)
            {
                BOW = commo.ReadBagOfWord();
                GetFieldCheck();// Trả ra chuỗi field được chọn
                string BugCurrent = "";// Bug current
                foreach (Control item in groupBox1.Controls)
                {
                    if (item.GetType().Name == "TextBox")
                    {
                        foreach (string s in Str)
                        {
                            if (s == item.Name)
                            {
                                BugCurrent += item.Text + " ";
                            }
                        }
                    }
                }
                //Tìm duplicate bug theo VSM
                if (BugCurrent != "")
                {
                    CheckDulicate(BugCurrent);
                    ShowResultSearch(bug_duplicate, dataGridView2);
                    ShowResultSearch(temp_duplicate, gvTemp);
                }

                //Tìm kiếm theo độ tương đồng 
                if (BugCurrent != "")
                {
                    N = dtBuild.Rows.Count;
                    BR_length = double.Parse(BOW.Count.ToString()); //Độ dài của tài liệu (túi từ)
                    d_avg = BR_length / double.Parse(N.ToString()); // Độ dài trung bình tính trên toàn bộ bug report
                    
                    ListResult = cal.Score(BugCurrent, dtBuild, BOW, Str, N, d_avg);
                }
                ShowResultSearch(ListResult,dataGridView1);
            }
           // VisibleBtn();
        }

        private void ShowResultSearch(Dictionary<string, double> listResult,DataGridView dtg)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Bug Report");

            List<double> value = new List<double>();
            foreach (string s in listResult.Keys)
            {
                value.Add(double.Parse(listResult[s].ToString()));
            }
            value.Sort();
            value.Reverse();           

            for (int i = 0; i < value.Count; i++)
            {
                foreach (string s in listResult.Keys)
                {
                    if (double.Parse(listResult[s].ToString()) == value[i])
                    {
                        DataRow row;
                        row = dt.NewRow();
                        row["Bug Report"] = s;
                        dt.Rows.Add(row);
                        listResult.Remove(s);
                        break;
                    }
                }
            }
            dtg.DataSource = dt;
            dtg.AutoResizeColumn(0);           
            
        }

        private void VisibleBtn()
        {
            btnSave.Enabled = false;
            btnSearch.Enabled = false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtthreshold_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (double.Parse(txtthreshold.Text) > 1 || double.Parse(txtthreshold.Text) < 0)
                {
                    MessageBox.Show("Threshold non larger 1 or less than 0");
                }
                else
                {
                    threshold = double.Parse(txtthreshold.Text);
                }
            }
            catch {
                MessageBox.Show("incorrect format");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            string File = openFileDialog1.FileName;
            if (string.IsNullOrEmpty(File))
                return;
            txtPath.Text = File;
            if (txtPath.Text != "")
            {
                DataTable dtBuild = connect.getDataFromXLS(txtPath.Text);
                if (dtBuild != null)
                {
                    foreach (DataColumn item in dtBuild.Columns)
                    {
                        bool conti = false;
                        foreach (Control ct in groupBox1.Controls)
                        {
                            if (ct.GetType().Name == "TextBox")
                            {
                                if (ct.Name.ToString() == item.ToString())
                                {
                                    ct.Text = item.Table.Rows[0][item.ToString()].ToString();
                                    conti = true;
                                }
                            }
                            if (conti == true)
                                break;
                        }
                    }
                }
            }
        }

        private void ImportExcel(int numberRow)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = false;
            saveFileDialog1.FileName = path;
            Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(saveFileDialog1.FileName);
            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
            int i = 1;
            //   i2 = Count_Cell();
            foreach (Control item in groupBox1.Controls)
            {
                if (item.GetType().Name == "TextBox")
                {
                    ws.Cells[numberRow + 1, i] = item.Text;
                    i++;
                }
            }
            wb.Save();
            wb.Close(true, null, null);
            app.Quit();
            releaseObject(ws);
            releaseObject(wb);
            releaseObject(app);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataTable dtBuild = connect.getDataFromXLS(path);
            ImportExcel(dtBuild.Rows.Count);
        }

    }
}
